package com.example.g7640.config.interceptor;

import com.alibaba.fastjson.JSONObject;
import com.example.g7640.builder.ResultBuilder;
import com.example.g7640.dto.SessionDto;
import com.example.g7640.dto.common.Result;
import com.example.g7640.util.SessionLocal;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;

@Slf4j
@Component
public class LoginInterceptor extends HandlerInterceptorAdapter {


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        HttpSession session = request.getSession();
        SessionDto sessionDto = (SessionDto)session.getAttribute(SessionLocal.SESSION);
        if(sessionDto == null){
            responseFailMsg(ResultBuilder.buildFail(600,"您当前未登录"),response);
            return false;
        }
        SessionLocal.setSession(sessionDto);
        return true;
    }



    private <T> void responseFailMsg(Result<T> result, HttpServletResponse response) throws IOException {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json");
        PrintWriter pw = response.getWriter();
        pw.print(JSONObject.toJSONString(result));
//        response.sendRedirect("http://81.68.102.150/api/wx/oauth/getOAuth2FirstLoginUrl");
//        response.setHeader("Access-Control-Allow-Origin","*");
//        response.setHeader("Access-Control-Max-Age","3600");
//        response.setHeader("Access-Control-Allow-Methods","*");
//        response.setHeader("Access-Control-Allow-Headers","*");
    }
}
